package com.android.djlmapp.activity.my;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.adapter.my.DuiZhangAdapter;
import com.android.djlmapp.adapter.my.ShaiXuanAdapter;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseActivity;
import com.android.djlmapp.dialog.DuiZhangPopup;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.model.home.ShaiXuanInfo;
import com.android.djlmapp.model.my.DuiZhangInfo;
import com.android.djlmapp.tools.global.ToastUtils;
import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.refresh_view.pullrecyclerview.PullRecyclerView;
import org.refresh_view.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class DuiZhangActivity extends BaseActivity {
    public static final String TAG = "djlm-my: ";

    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.home_iv_readpoint)
    ImageView homeIvReadpoint;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.tv_top_jump)
    TextView tvTopJump;
    @BindView(R.id.dz_pull_recycler_view)
    PullRecyclerView mPullRecyclerView;

    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectNetErrorLayout;

    private Unbinder mUnbinder;
    private DuiZhangAdapter mAdapter;
    private Context mContext;
    private boolean isHadData = false;
    int height;
    private int mPageSize = 1;
    //是否需要清空列表数据
    private boolean isClearData = false;
    private PopupWindow popWindow;
    private String msg;
    private int selectedIndex = 0;
    private List<String> listData = new ArrayList<>();
    private String errMsg = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dui_zhang);
        mUnbinder = ButterKnife.bind(this);
        mContext = getActivity();

        initView();
        initData();
    }

    @Override
    protected void initView() {
        llTopBack.setVisibility(View.VISIBLE);
        ivTopMsg.setVisibility(View.GONE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.GONE);
        tvTopJump.setText("筛选");
        tvTopJump.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tvTopJump.setVisibility(View.VISIBLE);
        tvName.setText("对账明细");

    }

    @Override
    protected void initData() {

        mAdapter = new DuiZhangAdapter(this);

        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        mPullRecyclerView.setColorSchemeResources(R.color.colorAccent);
        mPullRecyclerView.setAdapter(mAdapter);
        mPullRecyclerView.enableLoadMore(false);

        mPullRecyclerView.enablePullRefresh(true);
        // 开启下拉刷新，默认即为true，可不用设置

        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                isClearData = true;
                isHadData = false;
                mPullRecyclerView.enableLoadMore(true);
                mPageSize = 1;

                reqInfo(msg);
            }

            @Override
            public void onLoadMore() {
                mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip);
                // 开启数据全部加载完成时的底部提示，默认为false
                reqInfo(msg);
            }
        });

        mPullRecyclerView.autoRefresh();
        mAdapter.setOnItemClickListener(new DuiZhangAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DuiZhangInfo.DataBean item) {
                DuiZhangPopup.setInfo(item);
                new DuiZhangPopup(mContext).showPopupWindow();
            }
        });

        MyApplication.getInstance().getHttpTools().getKaiKaHomeData(GlobalUrls.DUIZHANG_SELECT, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    Gson gson = new Gson();
                    ShaiXuanInfo info = gson.fromJson(response.body(), ShaiXuanInfo.class);
                    if (info != null) {
                        if (info.getCode() == 200) {
                            listData = info.getData();
                            errMsg = "";
                        } else {
                            listData.clear();
                            listData.add("全部");
                            errMsg = info.getMsg();
                        }
                    } else {
                        listData.clear();
                        listData.add("全部");
                        errMsg = "未获取到数据";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    listData.clear();
                    listData.add("全部");
                    errMsg = "数据解析异常";
                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                listData.clear();
                listData.add("全部");
                errMsg = "网络或服务器错误";
            }
        });
    }


    private void reqInfo(String msg) {
        MyApplication.getInstance().getHttpTools().duizhang(mPageSize, msg, mStringCallBack);
    }

    private StringCallback mStringCallBack = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            try {
                DuiZhangInfo messageEntity = new Gson().fromJson(response.body(), DuiZhangInfo.class);
                if (messageEntity != null) {
                    List<DuiZhangInfo.DataBean> msgs = messageEntity.getData();

                    if ("200".equals("" + messageEntity.getCode()) && msgs.size() > 0) {
                        normalLayout();

                        if (isClearData) {
                            isClearData = false;
                            isHadData = false;
                            mAdapter.clear();
                            mPageSize = 1;
                        }

                        if (msgs.size() >= 10) {
                            mPageSize++;
                            mPullRecyclerView.enableLoadMore(true);
                            isHadData = true;
                        } else {
                            mPullRecyclerView.enableLoadMore(false);
                            isHadData = false;
                        }
                        mAdapter.addAll(msgs);

                    } else if ("2001".equals("" + messageEntity.getCode()) && mPageSize > 1) {
                        mPullRecyclerView.enableLoadMore(false);
                        isHadData = false;
                    } else {
                        mAdapter.clear();
                        Log.i(TAG, "200 else");
                        String wanningMsg = messageEntity.getMsg();
                        showErrorLayout(false, wanningMsg);
                    }
                } else {
                    mAdapter.clear();
                    showErrorLayout(false, "服务端异常");
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public void onError(Response<String> response) {
            if (mPullRecyclerView != null) {
                isClearData = false;
                showErrorLayout(true, getString(R.string.connect_sever_error_msg));
            }

        }

        @Override
        public void onFinish() {
            if (mPullRecyclerView != null) {
                mPullRecyclerView.stopLoadMore();
                mPullRecyclerView.stopRefresh();
            }
        }
    };

    @OnClick({R.id.ll_top_back, R.id.tv_top_jump})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_top_back:
                finish();
                break;
            case R.id.tv_top_jump:
                initPopWindow(view);
                if (!TextUtils.isEmpty(errMsg)) {
                    ToastUtils.showShortToast(DuiZhangActivity.this, errMsg);
                }
                break;
        }

    }

    private void initPopWindow(View v) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.duizhang_popup, null);

        //1.构造一个PopupWindow，参数依次是加载的View，宽高
        popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效

        //设置popupWindow显示的位置，参数依次是参照View，x轴的偏移量，y轴的偏移量
        popWindow.showAsDropDown(pageTitleLayout);
        shaixuan(view, listData);
    }

    private void shaixuan(View view, List<String> listData) {
        GridView gridView = view.findViewById(R.id.grid_sx);
        ShaiXuanAdapter shaiXuanAdapter = new ShaiXuanAdapter(this, listData, selectedIndex);
        gridView.setAdapter(shaiXuanAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        popWindow.dismiss();
                        msg = "";

                        break;
                    default:
                        msg = listData.get(position);
                        popWindow.dismiss();
                        break;

                }
                Log.e("项目异常onItemClick", msg + "------onItemClick------" + position);
                shaiXuanAdapter.setSelectedIndex(position);
                shaiXuanAdapter.notifyDataSetInvalidated();
                selectedIndex = position;

                mPullRecyclerView.autoRefresh();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    /**
     * 显示布局
     *
     * @param isNetError  是否是网络错误
     * @param warnningMsg 提示信息
     */
    private void showErrorLayout(boolean isNetError, String warnningMsg) {
        mPullRecyclerView.enableLoadMore(false);
        if (isHadData) {
            normalLayout();
            ToastUtils.showShortToastSafe(mContext, warnningMsg);
        } else {
            if (isNetError) {
                connectNetErrorLayout();
            } else {
                noDataLayout();
            }
        }
    }

    /**
     * 无数据状态
     */
    private void noDataLayout() {
        Log.i(TAG, "无数据状态");
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 网络错误状态
     */
    private void connectNetErrorLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.GONE) {
            mNullDataLayout.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 正常布局状态
     */
    private void normalLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.VISIBLE || mNullDataLayout.getVisibility() == View.VISIBLE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
        }
    }
}
















